package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
	"github.com/gansidui/geohash"
	"github.com/qiniu/go/src/pkg/strings"
	"github.com/satori/go.uuid"
	"strconv"
	"time"
)

func init() {

}

type MsgPage struct {
	Page     int32 `json:"page"`
	PageNum  int32 `json:"pageNum"`
	PageSize int32 `json:"pageSize"`
	Data     []Msg `json:"data"`
}

/*Maptype
0= WGS84 / GPS硬件 / Google Earth / Google Maps 卫星模式
1= Google Maps 地图模式
2= 百度地图坐标
3= QQ腾讯地图坐标 / 高德地图坐标 / 阿里云地图坐标
4= MapBar图吧地图坐标*/
type Msg struct {
	MsgId       string `json:"id" orm:"pk"`
	UserId      string `json:"-" orm:"index"`
	Title       string `json:"title"`
	Content     string `form:"content" json:"content"`
	PushTimes   int64  `form:"push_time" json:"pushTimes"`
	CreateTimes int64  `form:"create_time" json:"createTimes"`
	Target      string `json:"target"`
	Channel     string `form:"channel" json:"channel"`
	Status      int8   `form:"status" json:"status"`
	Location    string `form:"location" json:"location"`
	Latlng      string `form:"latlng" json:"latlng"`
	MapType     int8   `form:"map_type" json:"mapType"`
	GeoHash     string `json:"-"`
}

/*neighbors := geohash.GetNeighbors(latitude, longitude, precision)
for _, hash = range neighbors {
fmt.Print(hash, " ")
}*/
func CreateMsg(msg *Msg) (err error) {
	o := orm.NewOrm()
	msg.MsgId = uuid.NewV4().String()
	msg.CreateTimes = time.Now().Unix()
	ll := strings.Split(msg.Latlng, ",")

	if len(ll) != 2 {
		err = errors.New("latlng must right")
		return
	}
	lat, err := strconv.ParseFloat(ll[0], 0)
	if err != nil {
		err = errors.New("latlng must be double")
		return
	}

	lon, err := strconv.ParseFloat(ll[1], 0)
	if err != nil {
		err = errors.New("latlng must be double")
		return
	}

	geohash, _ := geohash.Encode(lat, lon, 8)
	msg.GeoHash = geohash

	_, err = o.Insert(msg)
	return err
}

func GetMsgById(msgId string) (msg Msg, err error) {
	o := orm.NewOrm()
	msg = Msg{MsgId: msgId}
	err = o.Read(&msg, "MsgId")
	return
}

func UpdateStatus(msg *Msg) (num int64, err error) {
	o := orm.NewOrm()
	num, err=o.QueryTable("msg").
	Filter("UserId",msg.UserId).
	Filter("MsgId",msg.MsgId).
	Update(orm.Params{"Status":msg.Status})
	return
}

func UpdateContent(msg *Msg) (num int64, err error) {
	o := orm.NewOrm()
	num, err=o.QueryTable("msg").
	Filter("UserId",msg.UserId).
	Filter("MsgId",msg.MsgId).
	Update(orm.Params{"Content":msg.Content})
	return
}

func GetMsgListByNear(pages Pages) (msgs []Msg, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("msg").
		Limit(pages.PageSize, (pages.Page-1)*pages.PageSize).
		All(&msgs)
	return msgs, err
}
